<!DOCTYPE html>
<html>

<head>
	<title>商品管理-添加</title>
	<meta http-equiv="Content-Type" content="text/html; charset=UTF-8">
	<meta name="viewport"
		content="width=device-width,initial-scale=1,minimum-scale=1,maximum-scale=1,user-scalable=no" />
	<!-- 所有的 css js 资源 -->
	<link rel="stylesheet" href="https://unpkg.com/element-ui@2.13.0/lib/theme-chalk/index.css">
	<link rel="stylesheet" href="../../static/sa.css">
	<script src="https://unpkg.com/vue@2.6.10/dist/vue.js"></script>
	<script src="https://unpkg.com/http-vue-loader@1.4.2/src/httpVueLoader.js"></script>
	<script src="https://unpkg.com/element-ui@2.13.0/lib/index.js"></script>
	<script src="https://unpkg.com/jquery@3.4.1/dist/jquery.js"></script>
	<script src="https://www.layuicdn.com/layer-v3.1.1/layer.js"></script>
	<script src="../../static/sa.js"></script>
	<style type="text/css">
		.c-panel .el-form .c-label {
			width: 8em !important;
		}

		.c-panel .el-form .el-input {
			width: 350px;
		}

		.sku-table .el-input {
			width: 100%;
		}

		.image-uploader .el-upload {
			border: 1px dashed #d9d9d9;
			border-radius: 6px;
			cursor: pointer;
			position: relative;
			overflow: hidden;
		}

		.image-uploader .el-upload:hover {
			border-color: #409EFF;
		}

		.image-uploader-icon {
			font-size: 28px;
			color: #8c939d;
			width: 100px;
			height: 100px;
			line-height: 100px;
			text-align: center;
		}

		.product-image {
			width: 100px;
			height: 100px;
			display: block;
		}
	</style>
</head>

<body>
	<div class="vue-box" style="display: none;" :style="'display: block;'">
		<!-- ------- 内容部分 ------- -->
		<div class="s-body">
			<div class="c-panel">
				<div class="c-title">商品添加</div>
				<el-form v-if="m" :model="m" label-width="120px">
					<!-- 基本信息 -->
					<el-divider content-position="left">基本信息</el-divider>
					<sa-item name="商品名称" v-model="m.name" br></sa-item>
					<sa-item name="商品描述" v-model="m.description" type="textarea" br></sa-item>
					<sa-item name="商品价格" v-model="m.price" br></sa-item>
					<sa-item name="库存数量" v-model="m.stock" br></sa-item>
					<!-- <sa-item name="商品分类" v-model="m.categoryName" br></sa-item> -->
					<sa-item name="商品分类" br>
						<el-select v-model="m.categoryName" @change="generateAttributesByCategory">
							<!-- <el-option label="请选择" :value="0" disabled></el-option> -->
							<el-option v-for="item in sysTypeList" :label="item.name" :value="item.name"
								:key="item.id"></el-option>
						</el-select>
					</sa-item>
					<sa-item name="品牌名称" br>
						<el-select v-model="m.brandName">
							<!-- <el-option label="请选择" :value="0" disabled></el-option> -->
							<el-option v-for="item in sysBrandList" :label="item.name" :value="item.name"
								:key="item.id"></el-option>
						</el-select>
					</sa-item>
					<sa-item name="是否上架" br>
						<el-switch v-model="m.isActive" active-color="#13ce66" inactive-color="#ff4949">
						</el-switch>
					</sa-item>

					<!-- SKU信息 -->
					<el-divider content-position="left">SKU信息</el-divider>
					<div class="sku-table">
						<el-button type="primary" size="small" @click="addSku"
							style="margin-bottom: 10px">添加SKU</el-button>
						<el-table :data="m.skus" border>
							<el-table-column label="SKU编码">
								<template slot-scope="scope">
									<el-input v-model="scope.row.skuCode"></el-input>
								</template>
							</el-table-column>
							<el-table-column label="价格">
								<template slot-scope="scope">
									<el-input v-model="scope.row.price" type="number"></el-input>
								</template>
							</el-table-column>
							<el-table-column label="库存">
								<template slot-scope="scope">
									<el-input v-model="scope.row.stock" type="number"></el-input>
								</template>
							</el-table-column>
							<el-table-column label="操作" width="100">
								<template slot-scope="scope">
									<el-button type="danger" size="mini" @click="removeSku(scope.$index)">删除</el-button>
								</template>
							</el-table-column>
						</el-table>
					</div>

					<!-- 商品图片 -->
					<el-divider content-position="left">商品图片</el-divider>
					<div class="image-list">
						<el-upload class="image-uploader" action="http://localhost:8080/files/upload" name="image" :show-file-list="false"
							:on-success="handleImageSuccess" :before-upload="beforeImageUpload">
							<i class="el-icon-plus image-uploader-icon"></i>
						</el-upload>
						<el-table :data="m.images" border style="margin-top: 10px">
							<el-table-column label="图片">
								<template slot-scope="scope">
									<img :src="imagePreviewUrl + scope.row.imageUrl" class="product-image">
								</template>
							</el-table-column>
							<el-table-column label="是否主图" width="100">
								<template slot-scope="scope">
									<el-switch v-model="scope.row.isMain"></el-switch>
								</template>
							</el-table-column>
							<el-table-column label="操作" width="100">
								<template slot-scope="scope">
									<el-button type="danger" size="mini"
										@click="removeImage(scope.$index)">删除</el-button>
								</template>
							</el-table-column>
						</el-table>
					</div>

					<!-- 商品属性 -->
					<el-divider content-position="left">商品属性</el-divider>
					<div class="attribute-table">
						<el-button type="primary" size="small" @click="addAttribute"
							style="margin-bottom: 10px; margin-right: 10px">添加属性</el-button>
						<el-button type="success" size="small" @click="generateAttributesByCategory"
							style="margin-bottom: 10px">重新生成属性</el-button>
						<el-table :data="m.attributes" border>
							<el-table-column label="属性名">
								<template slot-scope="scope">
									<el-input v-model="scope.row.attributeName"></el-input>
								</template>
							</el-table-column>
							<el-table-column label="属性值">
								<template slot-scope="scope">
									<el-input v-model="scope.row.attributeValue"></el-input>
								</template>
							</el-table-column>
							<el-table-column label="操作" width="100">
								<template slot-scope="scope">
									<el-button type="danger" size="mini"
										@click="removeAttribute(scope.$index)">删除</el-button>
								</template>
							</el-table-column>
						</el-table>
					</div>

					<sa-item name="" br class="s-ok">
						<el-button type="primary" icon="el-icon-plus" @click="ok()">保存</el-button>
					</sa-item>
				</el-form>
			</div>
		</div>
		<!-- ------- 底部按钮 ------- -->
		<div class="s-foot">
			<el-button type="primary" @click="ok()">确定</el-button>
			<el-button @click="sa.closeCurrIframe()">取消</el-button>
		</div>
	</div>
	<script>
		var app = new Vue({
			components: {
				"sa-item": httpVueLoader('../../sa-frame/com/sa-item.vue'),
			},
			el: '.vue-box',
			data: {
				m: null,// 实体对象 
				sysTypeList: [], // 商品类别列表
				sysBrandList: [], // 品牌列表
				imagePreviewUrl: 'http://8.134.184.130:8008/images/' // 图片预览路径
			},
			methods: {
				async getCategoryList() { //  获取商品分类列表
					try {
						let res = await $.ajax({
							url: 'http://localhost:8080/category/listCategory',
							type: 'GET',
							data: {
								pageNo: 1,
								pageSize: 100
							}
						});
						this.sysTypeList = res.list;
						// console.log("CategoryList:");
						// console.log(res);
					} catch (err) {
						console.log(err);
					}
				},
				async getCategory() { // 获取商品分类
					try {
						let res = await $.ajax({
							url: 'http://localhost:8080/category/getCategory',
							type: 'GET',
							data: {
								name: this.m.categoryName
							}
						});
						// console.log("Category:");
						// console.log(res);
						this.m.categoryId = res.id;
					} catch (err) {
						console.log(err);
					}
				},
				async getBrandList() { //  获取品牌列表
					try {
						let res = await $.ajax({
							url: 'http://localhost:8080/brand/listBrand',
							type: 'GET',
							data: {
								pageNum: 1,
								pageSize: 100
							}
						});
						this.sysBrandList = res.list;
						// console.log("BrandList:");
						// console.log(res);
					} catch (err) {
						console.log(err);
					}
				},
				async getBrand() { // 获取品牌
					try {
						let res = await $.ajax({
							url: 'http://localhost:8080/brand/getBrand',
							type: 'GET',
							data: {
								name: this.m.brandName
							}
						});
						// console.log("Brand:");
						// console.log(res);
						this.m.brandId = res.id;
					} catch (err) {
						console.log(err);
					}
				},
				// 创建一个默认Model 
				createModel: function () {
					return {
						id: null,
						name: '',			// 商品名称
						description: '',		// 商品描述
						price: null,			// 商品价格
						stock: null,			// 库存数量
						isActive: true,		// 是否上架
						categoryName: '',	// 商品分类
						brandName: '',		// 品牌名称
						categoryId: null,   // 商品分类ID
						brandId: null,		// 品牌ID
						skus: [],			// SKU列表
						images: [],			// 图片列表
						attributes: [
							// 自动生成的常用属性
							{
								productId: null,
								attributeName: '颜色',
								attributeValue: ''
							},
							{
								productId: null,
								attributeName: '尺寸',
								attributeValue: ''
							}
						]		// 属性列表
					}
				},
				// 添加SKU
				addSku: function () {
					// 生成SKU编码
					const skuCodes = this.generateSkuCode();
					this.m.skus.push({
						productId: null,
						skuCode: skuCodes,
						price: this.m.price || null,  // 使用主商品价格
						stock: this.m.stock || null   // 使用主商品库存
					});
					
				},
				// 生成SKU编码
				generateSkuCode: function() {
					// 获取商品名称的前几个字符作为前缀
					const prefix = this.m.name ? this.m.name.substring(0, 6).toUpperCase().replace(/\s+/g, '') : 'PROD';
					// 生成随机颜色
					const colors = ['BLACK', 'WHITE', 'RED', 'BLUE', 'GOLD', 'SILVER'];
					const color = colors[Math.floor(Math.random() * colors.length)];
					// 生成随机容量
					const capacities = ['64GB', '128GB', '256GB', '512GB', '1TB'];
					const capacity = capacities[Math.floor(Math.random() * capacities.length)];
					// 组合SKU编码
					return `${prefix}-${color}-${capacity}`;
				},
				// 删除SKU
				removeSku: function (index) {
					this.m.skus.splice(index, 1);
				},
				// 图片上传前的处理
				beforeImageUpload: function (file) {
					const isImage = file.type.indexOf('image/') === 0;
					const isLt5M = file.size / 1024 / 1024 < 5;

					if (!isImage) {
						this.$message.error('只能上传图片文件!');
						return false;
					}
					if (!isLt5M) {
						this.$message.error('图片大小不能超过 5MB!');
						return false;
					}
					return true;
				},
				// 图片上传成功的处理
				handleImageSuccess: function (res, file) {
					console.log("上传响应:", res);
					console.log("文件信息:", file);

					// 根据后端返回的 ResultVO 格式获取图片URL
					let imageUrl = '';
					if (res && res.data) {
						imageUrl = res.data; // ResultVO 中的 data 字段包含文件路径
					} else if (res && res.url) {
						imageUrl = res.url; // 兼容其他可能的格式
					} else {
						console.error("无法获取图片URL:", res);
						this.$message.error('图片上传失败');
						return;
					}

					// 检查是否是完整URL
					let imageFileName = '';
					if (imageUrl.startsWith('http://') || imageUrl.startsWith('https://')) {
						// 如果是完整URL，提取文件名
						const fileNameMatch = imageUrl.match(/\/([^\/]+)$/);
						if (fileNameMatch) {
							imageFileName = fileNameMatch[1]; // 获取文件名部分
						} else {
							imageFileName = imageUrl; // 如果没有匹配到，使用完整URL
						}
					} else {
						// 如果只是文件名，直接使用
						imageFileName = imageUrl;
					}

					console.log("处理的图片文件名:", imageFileName);

					this.m.images.push({
						productId: null,
						imageUrl: imageFileName, // 使用处理后的文件名
						isMain: this.m.images.length === 0 // 第一张图片默认为主图
					});
					
					this.$message.success('图片上传成功');
				},
				// 删除图片
				removeImage: function (index) {
					this.m.images.splice(index, 1);
				},
				// 添加属性
				addAttribute: function () {
					this.m.attributes.push({
						productId: null,
						attributeName: '',
						attributeValue: ''
					});
				},
				// 删除属性
				removeAttribute: function (index) {
					this.m.attributes.splice(index, 1);
				},
				// 根据商品分类自动生成属性
				generateAttributesByCategory: function() {
					if (!this.m.categoryName) return;
					
					// 清空现有属性
					this.m.attributes = [];
					
					// 根据分类生成不同的属性
					const categoryAttributes = {
						'手机': [
							{ attributeName: '尺寸', attributeValue: '' },
							{ attributeName: '存储容量', attributeValue: '' }
						],
						'电脑': [
							{ attributeName: '尺寸', attributeValue: '' },
							{ attributeName: '存储容量', attributeValue: '' }
						],
						'服装': [
							{ attributeName: '颜色', attributeValue: '' },
							{ attributeName: '尺码', attributeValue: '' }
						],
						'家具': [
							{ attributeName: '颜色', attributeValue: '' },
							{ attributeName: '尺寸', attributeValue: '' }
						],
						'食品饮料': [
							{ attributeName: '净含量', attributeValue: '' },
							{ attributeName: '保质期', attributeValue: '' }
						]
					};
					
					// 获取对应分类的属性，如果没有则使用默认属性
					const attributes = categoryAttributes[this.m.categoryName] || [
						{ attributeName: '颜色', attributeValue: '' },
						{ attributeName: '尺寸', attributeValue: '' }
					];
					
					// 转换为标准格式
					this.m.attributes = attributes.map(attr => ({
						productId: null,
						attributeName: attr.attributeName,
						attributeValue: attr.attributeValue
					}));
				},
				// 提交数据 
				ok: async function () {
					// 表单校验
					if (!this.m.name) return sa.msg('请输入商品名称');
					if (!this.m.price) return sa.msg('请输入商品价格');
					if (!this.m.stock) return sa.msg('请输入库存数量');
					if (!this.m.categoryName) return sa.msg('请选择商品分类');
					if (!this.m.brandName) return sa.msg('请输入品牌名称');

					try {
						// 等待获取分类ID和品牌ID
						await this.getCategory();
						await this.getBrand();

						// 构建仅包含必需字段的Product对象
						const product = {
							name: this.m.name,
							price: Number(this.m.price),
							stock: Number(this.m.stock),
							description: this.m.description,
							isActive: Number(this.m.isActive),
							categoryId: this.m.categoryId,
							brandId: this.m.brandId
						};

						console.log("准备发送的Product数据:", product);

						// 发送添加商品请求
						const productResult = await $.ajax({
							url: "http://localhost:8080/product/addProduct",
							type: "POST",
							contentType: "application/json",
							data: JSON.stringify(product),
							error: function(xhr, status, error) {
								console.error("添加商品失败:", {
									status: xhr.status,
									statusText: xhr.statusText,
									responseText: xhr.responseText,
									error: error
								});
							}
						});

						if (!productResult) {
							throw new Error('添加商品失败');
						}

						// 获取新创建的商品ID
						const productId = productResult;
						console.log("商品创建成功，ID:", productId);
						
						// 添加SKU
						if (this.m.skus && this.m.skus.length > 0) {
							console.log("准备添加SKU数据:", this.m.skus);
							for (const sku of this.m.skus) {
								try {
									const skuData = {
										...sku,
										productId: productId
									};
									console.log("发送SKU数据:", skuData);
									const skuResult = await $.ajax({
										url: "http://localhost:8080/productSku/addProductSku",
										type: "POST",
										contentType: "application/json",
										data: JSON.stringify(skuData),
										error: function(xhr, status, error) {
											console.error("添加SKU失败:", {
												status: xhr.status,
												statusText: xhr.statusText,
												responseText: xhr.responseText,
												error: error
											});
										}
									});
									console.log("SKU添加成功:", skuResult);
								} catch (error) {
									console.error("添加SKU失败:", error);
									throw new Error(`添加SKU失败: ${error.message}`);
								}
							}
						}

						// 添加图片
						if (this.m.images && this.m.images.length > 0) {
							console.log("准备添加图片数据:", this.m.images);
							for (const image of this.m.images) {
								try {
									const imageData = {
										...image,
										productId: productId
									};
									console.log("发送图片数据:", imageData);
									const imageResult = await $.ajax({
										url: "http://localhost:8080/productImage/addProductImage",
										type: "POST",
										contentType: "application/json",
										data: JSON.stringify(imageData),
										error: function(xhr, status, error) {
											console.error("添加图片失败:", {
												status: xhr.status,
												statusText: xhr.statusText,
												responseText: xhr.responseText,
												error: error
											});
										}
									});
									console.log("图片添加成功:", imageResult);
								} catch (error) {
									console.error("添加图片失败:", error);
									throw new Error(`添加图片失败: ${error.message}`);
								}
							}
						}

						// 添加属性
						if (this.m.attributes && this.m.attributes.length > 0) {
							console.log("准备添加属性数据:", this.m.attributes);
							for (const attribute of this.m.attributes) {
								try {
									const attributeData = {
										...attribute,
										productId: productId
									};
									console.log("发送属性数据:", attributeData);
									const attributeResult = await $.ajax({
										url: "http://localhost:8080/productAttributeValuer/addProductAttributeValue",
										type: "POST",
										contentType: "application/json",
										data: JSON.stringify(attributeData),
										error: function(xhr, status, error) {
											console.error("添加属性失败:", {
												status: xhr.status,
												statusText: xhr.statusText,
												responseText: xhr.responseText,
												error: error
											});
										}
									});
									console.log("属性添加成功:", attributeResult);
								} catch (error) {
									console.error("添加属性失败:", error);
									throw new Error(`添加属性失败: ${error.message}`);
								}
							}
						}

						sa.alert('商品添加成功', () => {
							this.clean();
							sa.closeCurrIframe();
						});

					} catch (error) {
						console.error("操作失败:", error);
						sa.alert('操作失败: ' + (error.message || '未知错误'));
					}
				},
				// 添加完成后的动作
				clean: function () {
					this.m = this.createModel();
				}
			},
			async mounted() {
				await this.getCategoryList();
				await this.getBrandList();
				// 初始化数据 
				this.m = this.createModel();
			}
		})
	</script>
</body>

</html>